package com.coocaa.x.service.litewebserver.webserver.servlet;

import android.content.Context;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lu on 15-9-8.
 */
public class ServletManager implements ServletLoader.ServletLoaderListener {
    private static Context mContext;
    private static ServletManager instance = new ServletManager();

    public static synchronized ServletManager getManager(Context context) {
        mContext = context;
        return instance;
    }


    private boolean bLoaded = false;
    private Map<String, Servlet> servletMap = new HashMap<String, Servlet>();

    public ServletManager() {
        ServletLoader.getLoader(mContext).setListener(this);
    }

    public synchronized void start() {
        if (bLoaded)
            return;
        ServletLoader.getLoader(mContext).loadServlet();
    }

    public synchronized void stop() {
        if (!bLoaded)
            return;
        synchronized (servletMap) {
            servletMap.clear();
        }
        ServletLoader.getLoader(mContext).releaseServlet();
        bLoaded = false;
    }

    public synchronized Servlet getServlet(String uri) {
        if (!bLoaded)
            return null;
        if (uri.startsWith(Servlet.SERVLET_HEADER)) {
            String id = Servlet.uriToServletID(uri);
            //如果当前没有处理uri的servlet，则返回默认的servlet，后续这里可以改成专门处理无servlet的情况
            if (id == null) {
                return ServletLoader.getLoader(mContext).getDefaultServlet();
            }
            return servletMap.get(id);
        } else if (uri.startsWith(Servlet.CACHE_HEADER))
            return ServletLoader.getLoader(mContext).getCacheServlet();
        else
            return ServletLoader.getLoader(mContext).getDefaultServlet();
    }

    @Override
    public void onLoadCompleted(List<Servlet> list) {
        for (Servlet s : list) {
            servletMap.put(s.getServletInfo().getID(), s);
        }
        bLoaded = true;
    }

    public List<Servlet.ServletInfo> getLoadedServletInfo() {
        Collection<Servlet> ss = servletMap.values();
        List<Servlet.ServletInfo> ret = new ArrayList<Servlet.ServletInfo>();
        for (Servlet s : ss) {
            ret.add(s.getServletInfo());
        }
        return ret;
    }
}
